/***
 * 产品多单位表格
 * 源码地址:http://www.htmleaf.com/Demo/201801274954.html
 * 以下为重构后代码
 * author:Katrina_CJ
 * @type {null}
 */

//重构T
var form = null;
layui.use(['form'], function () {
    form = layui.form;
});

var params = null;  		//初始化参数

var colsEdi = null;

function tableIsNull(tableId) {
    var table = $("#" + tableId);
    //表格为空的情况
    return table.find('tbody tr').length === 0;
}

//按钮组
var newColHtml = '<div class="">' +
    '<button id="edit_row" type="button" class="layui-btn layui-btn-sm layui-btn-primary" onclick="editRow(this);">' +
    '<span class="layui-icon layui-icon-edit" > </span>' +
    '</button>'+
    '<button id="delete_row" type="button" class="layui-btn layui-btn-sm layui-btn-primary" onclick="deleteRow(this);">' +
    '<span class="layui-icon layui-icon-delete" > </span>' +
    '</button>' +
    '<button id="finish_row" type="button" class="layui-btn layui-btn-sm layui-btn-primary" style="display:none;" onclick="finishRow(this);">' +
    '<span class="layui-icon layui-icon-ok" > </span>' +
    '</button>' +
    '<button id="cancel_row" type="button" class="layui-btn layui-btn-sm layui-btn-primary" style="display:none;" onclick="cancelRow(this);">' +
    '<span class="layui-icon layui-icon-close" > </span>' +
    '</button>' + '</div>';

var colEdicHtml = '<td name="buttons">' + newColHtml + '</td>'; //初始化按钮组

$.fn.SetEditable = function (options) {
    var defaults = {
        columnsEd: null,

        $addButton: null,

        onEdit: function () {

        },
        onBeforeDevare: function () {
        },
        onDevare: function (unit) {
            $.ajax({
                type: "post",
                url: Feng.ctxPath + "/units/delete",
                data: unit,
                dataType: "json",
                success: function (data) {
                    Feng.success("删除成功！");
                }
            });
        },
        onAdd: function () {
        }
    };
    params = $.extend(defaults, options);
    this.find('thead tr').append('<th name="buttons">操作</th>');  //添加操作表头
    this.find('tbody tr').append(colEdicHtml); //添加按钮组
    var $tabedi = this;
    //初始化添加表格按钮
    if (params.$addButton != null) {
        params.$addButton.click(function () {
            rowAddNew($tabedi.attr("id"));
        });
    }
    //Process "columnsEd" parameter
    if (params.columnsEd != null) {
        //Extract felds
        colsEdi = params.columnsEd.split(',');
    }
};

//表格迭代
function IterarCamposEdit($cols, tarea) {
    $cols.each(function () {
        if ($(this).attr('name') === 'buttons') return;
        if ($(this).attr('name') === 'def') return;
        tarea($(this));
    });
}


function show_edit(but) {
    $(but).parent().find('#finish_row').hide();
    $(but).parent().find('#cancel_row').hide();
    $(but).parent().find('#edit_row').show();
    $(but).parent().find('#delete_row').show();
    var $row = $(but).parents('tr');
    $row.attr('id', '');
}


function show_option(but) {
    $(but).parent().find('#finish_row').show();
    $(but).parent().find('#cancel_row').show();
    $(but).parent().find('#edit_row').hide();
    $(but).parent().find('#delete_row').hide();
    var $row = $(but).parents('tr');
    //赋予正在编辑状态
    $row.attr('id', 'editing');
}


/**是否编辑状态
 * @return {boolean}
 */
function rowIsEditing($row) {
    return $row.attr('id') === 'editing'
}

/**
 * 编辑完成
 * @param but
 */
function finishRow(but) {
    var $row = $(but).parents('tr');
    var $cols = $row.find('td');
    if (!rowIsEditing($row)) return;

    var unit_1 = null;
    var unit_2 = null;
    for (var i = 0; i < $cols.length; i++) {
        switch ($($cols[i]).attr('name')) {
            case 'unit_main':
                unit_1 = $($cols[i]).find('input').val();
                break;
            case 'units_deputy':
                unit_2 = $($cols[i]).find('input').val();
                break;
        }
    }
    if (unit_1 === '' || unit_2 === '') {
        Feng.error("请选择单位!");
        return false
    }


    var sum;
    IterarCamposEdit($cols, function ($td) {
        if ($td.attr('name') === 'auxiliary_number') {
            sum = $td.find('input').val();
            $td.html(sum);
        }
        if ($td.attr('name') === "settlement") {
            $td.html("1" + unit_1 + "=" + sum + unit_2);
        }
    });
    show_edit(but);
    params.onEdit($row);
}

/**
 * 取消编辑
 * @param but
 */
function cancelRow(but) {
    var $row = $(but).parents('tr');
    var $cols = $row.find('td');
    if (!rowIsEditing($row)) return;
    IterarCamposEdit($cols, function ($td) {
        if ($td.find('select').length !== 1) {
            var cont = $td.find('div').html();
            $td.html(cont);
        }
    });
    show_edit(but);
}

/**
 * 编辑行
 * @param but
 */
function editRow(but) {
    var $row = $(but).parents('tr');
    var $cols = $row.find('td');
    if (rowIsEditing($row)) return;
    IterarCamposEdit($cols, function ($td) {
        if ($td.attr("name") === "auxiliary_number") {
            var cont = $td.html();
            var div = '<div style="display: none;">' + cont + '</div>';
            var input = '<input class="layui-input" type="number"  value="' + cont + '">';
            $td.html(div + input);
        }
    });
    show_option(but);
}

/**
 * 删除ROW
 * @param but
 * @returns {boolean}
 */
function deleteRow(but) {
    var $row = $(but).parents('tr');
    var $tab_en_edic = $("#" + 'unitTable');
    if ($tab_en_edic.find('tr').length <= 2) {
        Feng.error("必须保留一个单位！");
        return false;
    } else {
        var cols = $($row).find("td");
        var unit = getRowDataDelete(cols);
        //TODO 删除ROW
        params.onBeforeDevare($row);
        $row.remove();
        if (unit.unitsId != null) {
            params.onDevare(unit);
        } else {
            params.onDevare();
        }
    }
}

/**
 * 添加表格
 * @param tableId
 */
function rowAddNew(tableId) {
    var table = $("#" + tableId);
    //表格为空的情况
    var rows = table.find('thead tr');
    if (tableIsNull(tableId)) {
        var cols = rows.find('th');
        var htmlDat = '';
        cols.each(function () {
            if ($(this).attr('name') === 'buttons') {
                htmlDat = htmlDat + colEdicHtml;  //这里只添加按钮组
            } else {
                htmlDat = htmlDat + '<td></td>';
            }
        });
        table.find('tbody').append('<tr>' + htmlDat + '</tr>');
    } else {
        //添加到最后一行，然后获取最后一行
        var lastTr = table.find('tr:last');
        lastTr.clone().appendTo(lastTr.parent());
        lastTr = table.find('tr:last');
        var tds = lastTr.find('td');
        IterarCamposEdit(tds, function (td) {
            if (td.attr("name") === "auxiliary_number") {
                td.html('');
            } else if (td.attr("name") === 'settlement') {
                td.html('');
            }

        });

    }
    params.onAdd();
    form.render('select');
}


// function TabvaroCSV(tabId, separator) {  //Convierte tabla a CSV
//     var datFil = '';
//     var tmp = '';
//     var $tab_en_edic = $("#" + tabId);  //Table source
//     $tab_en_edic.find('tbody tr').each(function () {
//         //Termina la edición si es que existe
//         if (ModoEdicion($(this))) {
//             $(this).find('#finish_row').click();  //acepta edición
//         }
//         var $cols = $(this).find('td');  //lee campos
//         datFil = '';
//         $cols.each(function () {
//             if ($(this).attr('name') == 'buttons') {
//                 //Es columna de botones
//             } else {
//                 datFil = datFil + $(this).html() + separator;
//             }
//         });
//         if (datFil != '') {
//             datFil = datFil.substr(0, datFil.length - separator.length);
//         }
//         tmp = tmp + datFil + '\n';
//     });
//     return tmp;
// }


/**
 * 获取删除的单位对象
 * @param cols
 */
function getRowDataDelete(cols) {
    var units = {};
    IterarCamposEdit(cols, function ($td) {
        switch ($td.attr('name')) {
            case 'units_id':
                units.unitsId = $td.find('input[name = "unitsId"]').val();
                break;
            case 'unit_main':
                units.unitsMain = $td.find('select').next().find('dd[class="layui-this"]').attr("lay-value");
                break;
            case 'def':
                break;
            case 'units_deputy':
                units.unitsDeputy = $td.find('select').next().find('dd[class="layui-this"]').attr("lay-value");
                break;
            case "auxiliary_number":
                units.unitsProportion = $td.text();
                break;
        }
    });
    return units;
}

$("#uploadBtn").click(function () {
    console.log(getAllData());

});

/**
 * 获取多单位集合
 * @param $rows
 */
function getAllData() {
    var $tab_en_edic = $("#unitTable");
    var trs = $tab_en_edic.find('tbody tr');
    var unitsArr = [];
    for (var i = 0; i < trs.length; i++) {
        var units = {};
        var tdArr = trs.eq(i).find("td");
        units.unitsId = tdArr.eq(0).find('input').val();
        units.unitsMain = tdArr.eq(1).find('select').next().find('dd[class="layui-this"]').attr("lay-value");
        units.unitsDeputy = tdArr.eq(3).find('select').next().find('dd[class="layui-this"]').attr("lay-value");
        units.unitsProportion = tdArr.eq(4).text();
        unitsArr.push(units);
    }
    return unitsArr;
}

/**
 * 判断集合是否有空数据
 * @param units
 */
function dataIsNull(units) {
    for (var i = 0; i < units.length; i++) {
        return units.unitsMain == null || units.unitsDeputy == null || units.unitsProportion == null;
    }
}
